package businessError

import (
	"fmt"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"grpc.getaway.adminspro.padmins.com/pkg/libs/db"
)

type ErrorInfo struct {
	Code int
	Msg  string
}

func (e *ErrorInfo) GetCode() int {
	return e.Code
}

func (e *ErrorInfo) GetMsg() string {
	return e.Msg
}

func (e *ErrorInfo) String() string {
	return fmt.Sprintf("business error: code = %d msg = %s", e.Code, e.Msg)
}

func (e *ErrorInfo) Error() string {
	return e.String()
}

func Error(code int, message string) *ErrorInfo {
	return &ErrorInfo{Code: code, Msg: message}
}

func Errorf(code int, format string, a ...interface{}) *ErrorInfo {
	return Error(code, fmt.Sprintf(format, a...))
}

func ErrorfByErrorInfo(e *ErrorInfo, a ...interface{}) *ErrorInfo {
	return Errorf(e.Code, e.Msg, a...)
}

func DbError(e *db.DbError) *ErrorInfo {
	return &ErrorInfo{Code: DataBaseError.Code, Msg: DataBaseError.Msg + ":" + e.Error()}
}

func ErrorInfoToRpcError(e *ErrorInfo) error {
	return status.Error(codes.Code(e.Code), e.Msg)
}

func RpcErrorToErrorInfo(e error) *ErrorInfo {
	rpcErr, b := status.FromError(e)

	if b == true {
		grpcStatus := rpcErr.Proto()
		return Error(int(grpcStatus.Code), grpcStatus.Message)
	}
	return nil
}
